const DB_NAME = 'myDatabase';
const DB_VERSION = 1;
const STORE_NAME = 'essay';

// 创建或打开数据库
const openDb = () => {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(DB_NAME, DB_VERSION);

    // 数据库升级（创建对象存储）
    request.onupgradeneeded = (event) => {
      const db = event.target.result;
      if (!db.objectStoreNames.contains(STORE_NAME)) {
        db.createObjectStore(STORE_NAME, {keyPath: 'id', autoIncrement: true});
      }
    };

    // 成功打开数据库
    request.onsuccess = (event) => {
      resolve(event.target.result);
    };

    // 失败
    request.onerror = (event) => {
      reject('IndexedDB Error: ' + event.target.errorCode);
    };
  });
};

// 封装操作
const indexedDbService = {
  // 添加数据
  addItem: (data) => {
    return openDb().then((db) => {
      return new Promise((resolve, reject) => {
        const transaction = db.transaction(STORE_NAME, 'readwrite');
        const store = transaction.objectStore(STORE_NAME);
        const request = store.add(data);

        request.onsuccess = () => resolve(request.result);
        request.onerror = (event) => reject(event.target.error);
      });
    });
  },

  // 获取所有数据
  getAllItems: () => {
    return openDb().then((db) => {
      return new Promise((resolve, reject) => {
        const transaction = db.transaction(STORE_NAME, 'readonly');
        const store = transaction.objectStore(STORE_NAME);
        const request = store.getAll();

        request.onsuccess = () => resolve(request.result);
        request.onerror = (event) => reject(event.target.error);
      });
    });
  },

  // 获取单个数据
  getItemById: (id) => {
    return openDb().then((db) => {
      return new Promise((resolve, reject) => {
        const transaction = db.transaction(STORE_NAME, 'readonly');
        const store = transaction.objectStore(STORE_NAME);
        const request = store.get(id);

        request.onsuccess = () => resolve(request.result);
        request.onerror = (event) => reject(event.target.error);
      });
    });
  },

  // 更新数据
  updateItem: (data) => {
    return openDb().then((db) => {
      return new Promise((resolve, reject) => {
        const transaction = db.transaction(STORE_NAME, 'readwrite');
        const store = transaction.objectStore(STORE_NAME);
        const request = store.put(data);

        request.onsuccess = () => resolve(request.result);
        request.onerror = (event) => reject(event.target.error);
      });
    });
  },

  // 删除数据
  deleteItem: (id) => {
    return openDb().then((db) => {
      return new Promise((resolve, reject) => {
        const transaction = db.transaction(STORE_NAME, 'readwrite');
        const store = transaction.objectStore(STORE_NAME);
        const request = store.delete(id);

        request.onsuccess = () => resolve(id);
        request.onerror = (event) => reject(event.target.error);
      });
    });
  }
};

export default indexedDbService;
